package com.jihu.mall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Maps;
import com.jihu.mall.auth.feign.MemberFeignService;
import com.jihu.mall.auth.feign.ThirdPartFeignService;
import com.jihu.mall.auth.vo.UserRegisterVo;
import com.jihu.mall.common.constant.AuthServerConstant;
import com.jihu.mall.common.exception.BizCodeEnum;
import com.jihu.mall.common.utils.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author jihu
 * @date 2021/4/10
 */
@Controller
public class LoginController {

    @Autowired
    private ThirdPartFeignService thirdPartFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MemberFeignService memberFeignService;

    /**
     * 发送一个请求直接跳转到一个页面
     * SpringMVC viewcontroller 将请求和页面映射过来
     * @return
     */
    @GetMapping("/sms/sendcode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone){

        //TODO 1.接口防刷
        String key = AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone;
        String redisCode = redisTemplate.opsForValue().get(key);
        if(StringUtils.isNotEmpty(redisCode)){
            Long time = Long.parseLong(redisCode.split("_")[1]);

            if((System.currentTimeMillis() - time) < 60000){
                //60秒内不能再发
                return R.error(BizCodeEnum.VAILD_SMS_CODE_EXCEPTION);
            }
        }
        //1.接口防刷。
        //2.验证码的再次校验。redis 存 key-phone value-code sms:code:手机号 -> 验证码
        String code = UUID.randomUUID().toString().substring(0, 5);

        //redis缓存验证码
        redisTemplate.opsForValue().set(key,code+"_"+System.currentTimeMillis(),10, TimeUnit.MINUTES);


        thirdPartFeignService.sendCode(phone,code);
        return R.ok();
    }

    @PostMapping("/register")
    public String register(@Valid UserRegisterVo vo, BindingResult result,
                           RedirectAttributes redirectAttributes){
        if(result.hasErrors()){
            return returnErrorCode(redirectAttributes, result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage)));
        }


        //真正注册，调用远程服务进行注册
        //1.校验验证码
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if(!StringUtils.isEmpty(redisCode)){
            if(redisCode.split("_")[0].equals(vo.getCode())){
                //删除验证码
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                //验证码通过 //正则注册，调用远程服务进行注册
                R r = memberFeignService.regitser(vo);
                if(0 == r.getCode()){
                    //注册成功回到首页，回到登录页

                    return "redirect:http://auth.gulimall.com/login.html";
                }else {
                    Map<String,String> errors = new HashMap<>();
                    errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
                    return returnErrorCode(redirectAttributes, errors);
                }
            }else {
                Map<String,String> errors = Maps.newHashMap();
                errors.put("code","验证码错误");
                return returnErrorCode(redirectAttributes, errors);
            }
        } else{
            Map<String,String> errors = Maps.newHashMap();
            errors.put("code","验证码错误");
            return returnErrorCode(redirectAttributes, errors);
        }
    }

    private String returnErrorCode(RedirectAttributes redirectAttributes, Map<String, String> errors) {
        redirectAttributes.addFlashAttribute("errors",errors);
        //校验出错，转发到注册页
        return "redirect:http://auth.gulimall.com/register.html";
    }


//    @GetMapping("/login.html")
//    public String loginPage(){
//        return "login";
//    }
//
//    @GetMapping("/register.html")
//    public String registerPage(){
//        return "register";
//    }
}
